package org.dromara.system.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.poi.ss.formula.functions.T;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.system.domain.vo.YzlYs7CameraVo;
import org.dromara.system.utils.PageByList;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.YzlSafetyCameraBo;
import org.dromara.system.domain.vo.YzlSafetyCameraVo;
import org.dromara.system.domain.YzlSafetyCamera;
import org.dromara.system.mapper.YzlSafetyCameraMapper;
import org.dromara.system.service.IYzlSafetyCameraService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 摄像头视频Service业务层处理
 *
 * @author fxnn
 * @date 2025-09-08
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class YzlSafetyCameraServiceImpl implements IYzlSafetyCameraService {

    private final YzlSafetyCameraMapper baseMapper;

    /**
     * 查询摄像头视频
     *
     * @param id 主键
     * @return 摄像头视频
     */
    @Override
    public YzlSafetyCameraVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询摄像头视频列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 摄像头视频分页列表
     */
    @Override
    public TableDataInfo<YzlSafetyCameraVo> queryPageList(YzlSafetyCameraBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<YzlSafetyCamera> lqw = buildQueryWrapper(bo);
        Page<YzlSafetyCameraVo> result = baseMapper.customPageList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的摄像头视频列表
     *
     * @param bo 查询条件
     * @return 摄像头视频列表
     */
    @Override
    public List<YzlSafetyCameraVo> queryList(YzlSafetyCameraBo bo) {
        LambdaQueryWrapper<YzlSafetyCamera> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoListDept(lqw);
    }

    private LambdaQueryWrapper<YzlSafetyCamera> buildQueryWrapper(YzlSafetyCameraBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<YzlSafetyCamera> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(YzlSafetyCamera::getCreateTime);
        lqw.eq(true,YzlSafetyCamera::getDelFlag,0);
        lqw.eq(bo.getDeptId() != null, YzlSafetyCamera::getDeptId, bo.getDeptId());
        lqw.eq(bo.getUserId() != null, YzlSafetyCamera::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getDeviceSerial()), YzlSafetyCamera::getDeviceSerial, bo.getDeviceSerial());
        lqw.eq(StringUtils.isNotBlank(bo.getEzopen()), YzlSafetyCamera::getEzopen, bo.getEzopen());
        lqw.eq(StringUtils.isNotBlank(bo.getEzopenTwo()), YzlSafetyCamera::getEzopenTwo, bo.getEzopenTwo());
        lqw.like(StringUtils.isNotBlank(bo.getCameraName()), YzlSafetyCamera::getCameraName, bo.getCameraName());
        lqw.eq(StringUtils.isNotBlank(bo.getAppKey()), YzlSafetyCamera::getAppKey, bo.getAppKey());
        lqw.eq(StringUtils.isNotBlank(bo.getAppSecret()), YzlSafetyCamera::getAppSecret, bo.getAppSecret());
        return lqw;
    }

    /**
     * 新增摄像头视频
     *
     * @param bo 摄像头视频
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(YzlSafetyCameraBo bo) {
        YzlSafetyCamera add = MapstructUtils.convert(bo, YzlSafetyCamera.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改摄像头视频
     *
     * @param bo 摄像头视频
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(YzlSafetyCameraBo bo) {
        YzlSafetyCamera update = MapstructUtils.convert(bo, YzlSafetyCamera.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(YzlSafetyCamera entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除摄像头视频信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 获取该萤石云设备下的萤石云播放设备信息列表
     * @param bo
     * @return
     */
    @Override
    public JSONObject cameraList(String accessToken, String deviceSerial) {


        //  获取指定设备的通道信息
        JSONObject deviceInfo = deviceInfo(accessToken, deviceSerial);
        //  获取单个设备信息
        JSONObject deviceInfoData = deviceInfo.getJSONObject("data");
        //  获取指定设备的通道信息
        JSONObject deviceCameraList = deviceCameraList(accessToken, deviceSerial);
        JSONArray deviceCameraListArray = deviceCameraList.getJSONArray("data");

        //  获取指定设备的通道信息（cameraList） 存入 获取单个设备信息（deviceInfoData） 里面
        if(deviceCameraListArray != null && !deviceCameraListArray.isEmpty()){
            deviceInfoData.put("cameraList", deviceCameraListArray);
        }
        //  hutool 序列化 null 问题
        String res = JSONObject.toJSONString(deviceInfoData, SerializerFeature.WRITE_MAP_NULL_FEATURES);

        return JSONObject.parseObject(res);
        /*LambdaQueryWrapper<YzlSafetyCamera> lqw = buildQueryWrapper(bo);
        List<YzlSafetyCamera> safetyCameraList = baseMapper.selectList(lqw);
        if(safetyCameraList!=null && !safetyCameraList.isEmpty()){
            for(YzlSafetyCamera camera:safetyCameraList){

            }
        }*/
    }

    @Override
    public TableDataInfo<YzlYs7CameraVo> cameraListPage(String accessToken, String deviceSerial, PageQuery pageQuery) {
        //  获取指定设备的通道信息
        //JSONObject deviceInfo = deviceInfo(accessToken, deviceSerial);
        //  获取单个设备信息
        //JSONObject deviceInfoData = deviceInfo.getJSONObject("data");
        //  获取指定设备的通道信息
        JSONObject deviceCameraList = deviceCameraList(accessToken, deviceSerial);
        JSONArray deviceCameraListArray = deviceCameraList.getJSONArray("data");
        Page<YzlYs7CameraVo> page = pageQuery.build();
        if(deviceCameraListArray==null){
            return TableDataInfo.build(page);
        }
        List<YzlYs7CameraVo> YzlYs7CameraVoList = JSONObject.parseArray(deviceCameraListArray.toJSONString(), YzlYs7CameraVo.class);
        List<YzlYs7CameraVo> list = PageByList.startPage(YzlYs7CameraVoList,pageQuery.getPageNum(),Integer.parseInt(page.getSize()+""));
        page.setRecords(list);
        page.setTotal(YzlYs7CameraVoList.size());
        TableDataInfo<YzlYs7CameraVo> kk = TableDataInfo.build(page);
        return kk;
    }

    @Override
    public String getAccessToken(String appKey,String appSecret){
        HttpRequest request = HttpUtil.createPost("https://open.ys7.com/api/lapp/token/get?appKey=" + appKey + "&appSecret=" + appSecret);
        cn.hutool.http.HttpResponse response = request.execute();
        String body = response.body();
        cn.hutool.json.JSONObject entries = JSONUtil.parseObj(body);
        return entries.getJSONObject("data").getStr("accessToken");
    }



    public JSONObject deviceInfo(String accessToken, String deviceSerial) {
        HttpRequest request = HttpUtil.createPost("https://open.ys7.com/api/lapp/device/info?" + "accessToken=" + accessToken + "&deviceSerial=" + deviceSerial);
        cn.hutool.http.HttpResponse response = request.execute();
        String body = response.body();
        return JSONObject.parseObject(body);
    }

    public com.alibaba.fastjson.JSONObject deviceCameraList(String accessToken, String deviceSerial) {
        HttpRequest request = HttpUtil.createPost("https://open.ys7.com/api/lapp/device/camera/list?" + "accessToken=" + accessToken + "&deviceSerial=" + deviceSerial);
        cn.hutool.http.HttpResponse response = request.execute();
        String body = response.body();
        return JSON.parseObject(body);
    }

}


